package com.szsky.sky.task;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.szsky.sky.dto.mq.Character;
import com.szsky.sky.dto.mq.ToZeroProducerDto;
import com.szsky.sky.entity.UmcCharOrgan;
import com.szsky.sky.entity.UmcOrgan;
import com.szsky.sky.entity.UmcPerson;
import com.szsky.sky.mapper.*;
import com.szsky.sky.pojo.Employee;
import com.szsky.sky.pojo.GuserInfo;
import com.szsky.sky.pojo.OaInSpurUser;
import com.szsky.sky.service.mq.AsyncMessageService;
import com.szsky.sky.task.vo.MqName;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Component
public class SendMqMessageTask {

    @Value("${send.mq.message.isExecute}")
    private Boolean isExecute;

//    @Value("${send.mq.message.departmentId}")
//    private String departmentId;

    @Resource
    private EmployeeMapper employeeMapper;

    @Resource
    private GuserInfoMapper guserInfoMapper;

    @Resource
    private OaInSpurUserMapper oaInSpurUserMapper;

    @Resource
    private UmcPersonMapper umcPersonMapper;

    @Resource
    private UmcCharOrganMapper umcCharOrganMapper;

    @Resource
    private UmcOrganMapper umcOrganMapper;

    @Resource
    private AsyncMessageService asyncMessageService;

    @Resource
    private MqName mqName;

    @Scheduled(cron = "${send.mq.message.cronSync}")
    public void sendMqMessage() {
        if (CollectionUtil.isNotEmpty(mqName.getDepartmentIdList()) || CollectionUtil.isNotEmpty(mqName.getNameList())){
            log.info("开始执行发送mq消息同步数据至零信任开始");
            sendMqMessageTask();
            log.info("开始执行发送mq消息同步数据至零信任结束");
        }else {
            log.info("没有要同步得部门是数据同步数据至零信任任务结束");
        }

    }

    public void sendMqMessageTask() {

        if (isExecute){
            try {
                List<ToZeroProducerDto> toZeroProducerDtos  = new ArrayList<>();
                // 同步勾选得人员
                List<Employee> employees = Collections.emptyList();

                if (CollectionUtil.isNotEmpty(mqName.getDepartmentIdList())){

                    List<String> departmentIdList = mqName.getDepartmentIdList();

                    QueryWrapper<Employee> employeeQueryWrapper = new QueryWrapper<>();

                    for (String departmentId : departmentIdList) {
                        employeeQueryWrapper.or().like("stru_path",departmentId);
                    }

                    //1. 查询人员基本信息
                    employees = employeeMapper.selectList(employeeQueryWrapper);
                    log.info("人员信息：{}", JSONObject.toJSONString(employees));
                }

                if (CollectionUtil.isNotEmpty(mqName.getNameList())){

                    List<UmcPerson> umcPersonByUserId = umcPersonMapper.getUmcPersonByUserId(mqName.getNameList());

                    List<String> idCarNumberList = umcPersonByUserId.stream().map(UmcPerson::getCertNum).collect(Collectors.toList());

                    QueryWrapper<Employee> employeeQueryWrapper = new QueryWrapper<>();
                    employeeQueryWrapper.in("ID_CARD_NUM",idCarNumberList);
                    //1. 查询人员基本信息
                    employees = employeeMapper.selectList(employeeQueryWrapper);
                    log.info("人员信息：{}", JSONObject.toJSONString(employees));
                }

                if (CollectionUtil.isNotEmpty(employees)) {
                    Map<String, Employee> employeeMap = employees.stream().collect(Collectors.toMap(Employee::getIdCardNum, item -> item, (key1, key2) -> key1));

                    //2. 将人员基本信息集合转换为身份证号集合

                    List<String> idCarNumList = employees.stream().map(Employee::getIdCardNum).collect(Collectors.toList());

                    //3. 使用身份证号查询 g_user_info信息
                    LambdaQueryWrapper<GuserInfo> guserInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
                    guserInfoLambdaQueryWrapper.in(GuserInfo::getIdNumber, idCarNumList);
                    List<GuserInfo> guserInfos = guserInfoMapper.selectList(guserInfoLambdaQueryWrapper);

                    // 4. 获取g_user_info信息中的id
                    List<String> gUserInfoIdList = guserInfos.stream().map(GuserInfo::getId).collect(Collectors.toList());

                    // 5. 使用g_user_info信息中的id查询 oa_inpur_user 信息

                    LambdaQueryWrapper<OaInSpurUser> oaInSpurUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
                    oaInSpurUserLambdaQueryWrapper.in(OaInSpurUser::getOaUserId, gUserInfoIdList);

                    List<OaInSpurUser> oaInSpurUsers = oaInSpurUserMapper.selectList(oaInSpurUserLambdaQueryWrapper);

                    // 6. 获取uc_uid
                    List<String> ucUidList = oaInSpurUsers.stream().map(OaInSpurUser::getInspurId).collect(Collectors.toList());


                    List<UmcPerson> umcPersonList = umcPersonMapper.getUmcPersonByUcUid(ucUidList);

                    List<String> organIdList = employees.stream().map(Employee::getDepartmentId).collect(Collectors.toList());

                    LambdaQueryWrapper<UmcCharOrgan> charOrganLambdaQueryWrapper = new LambdaQueryWrapper<>();
                    charOrganLambdaQueryWrapper.in(UmcCharOrgan::getOrganId, organIdList);
                    List<UmcCharOrgan> umcCharOrganList = umcCharOrganMapper.selectList(charOrganLambdaQueryWrapper);

                    Map<String, UmcCharOrgan> umcCharOrganMap = umcCharOrganList.stream().collect(Collectors.toMap(UmcCharOrgan::getOrganId, item -> item, (key1, key2) -> key1));

                    LambdaQueryWrapper<UmcOrgan> umcOrganLambdaQueryWrapper = new LambdaQueryWrapper<>();
                    umcOrganLambdaQueryWrapper.in(UmcOrgan::getOrganId, organIdList);
                    List<UmcOrgan> umcOrganList = umcOrganMapper.selectList(umcOrganLambdaQueryWrapper);

                    Map<String, UmcOrgan> umcOrganMap = umcOrganList.stream().collect(Collectors.toMap(UmcOrgan::getOrganId, item -> item, (key1, key2) -> key1));

                    for (UmcPerson umcPerson : umcPersonList) {
                        ToZeroProducerDto toZeroProducerDto = new ToZeroProducerDto();

                        toZeroProducerDto.setOper("U");
                        toZeroProducerDto.setUcUid(umcPerson.getUcUid());
                        toZeroProducerDto.setUserId(umcPerson.getUserId());
                        toZeroProducerDto.setUserName(umcPerson.getUName());
                        toZeroProducerDto.setSex(umcPerson.getSex());
                        toZeroProducerDto.setAccoutStatus(umcPerson.getStatus());
                        toZeroProducerDto.setAuthLevel(umcPerson.getAuthenLevel());
                        toZeroProducerDto.setCertNum(umcPerson.getCertNum());
                        toZeroProducerDto.setPhone(umcPerson.getPhone());
                        toZeroProducerDto.setEmail(umcPerson.getEmail());
                        toZeroProducerDto.setBirthdate(umcPerson.getBirthdate() == null ? "" : umcPerson.getBirthdate());
                        toZeroProducerDto.setOfficePhone(umcPerson.getOfficePhone() == null ? "" : umcPerson.getOfficePhone());

                        List<Character> characters = new ArrayList<>();

                        Character character = new Character();
                        character.setOper(toZeroProducerDto.getOper());
                        Employee employee = employeeMap.get(umcPerson.getCertNum());
                        if (Objects.nonNull(employee) && org.apache.commons.lang3.StringUtils.isNotBlank(employee.getDepartmentId())) {
                            if (Objects.nonNull(umcCharOrganMap.get(employee.getDepartmentId()))){
                                character.setChartId(umcCharOrganMap.get(employee.getDepartmentId()).getCharId() == null ? "" : umcCharOrganMap.get(employee.getDepartmentId()).getCharId());
                                character.setCharId(umcCharOrganMap.get(employee.getDepartmentId()).getCharId());
                            }
                            if (org.apache.commons.lang3.StringUtils.isNotBlank(employee.getTechPosCode())) {
                                character.setChartName(employee.getTechPosCode());
                                character.setCharName(employee.getTechPosCode());
                            } else if (org.apache.commons.lang3.StringUtils.isNotBlank(employee.getJobTitleCode())) {
                                character.setChartName(employee.getJobTitleCode());
                                character.setCharName(employee.getJobTitleCode());
                            } else {
                                character.setChartName("员工");
                                character.setCharName("员工");
                            }
                            character.setOrganId(employee.getDepartmentId());
                            // TODO roles 待确定
                            character.setRoles("");
                            if (Objects.nonNull(umcCharOrganMap.get(employee.getDepartmentId()))){
                                character.setSortNo(umcCharOrganMap.get(employee.getDepartmentId()).getSortNo());
                                character.setOrganName(umcOrganMap.get(employee.getDepartmentId()).getOrganName());
                                character.setOrganType(umcOrganMap.get(employee.getDepartmentId()).getOrganType());
                            }
                            character.setBdefault(Boolean.TRUE);

                        }

                        characters.add(character);
                        toZeroProducerDto.setCharacters(characters);
                        // 插入集合
                        toZeroProducerDtos.add(toZeroProducerDto);
                    }


                    // 2. 异步启动消息发送任务，不阻塞当前请求
                    asyncMessageService.startAsyncSending(toZeroProducerDtos);
                }
            }catch (Exception e){
                log.error("发送mq消息同步数据至零信任时发生异常：{}",e.getMessage());
                e.printStackTrace();
            }
        }else {
            log.warn("配置中配置不执行mq定时任务");
        }


    }
}
